// Src.js
(function ($) {
    $.calendar = {
        "options": {
        },
       "debug": true
    };

    function jQueryCalendar(options) {
        this.$el = this;
        this.options = _.extend($.calendar.options, options);
        this.render = render;

        this.currentDate = resetDate();
        this.render();

        drawDays.apply(this, []);
    }

    function resetDate() {
        return new Date();
    }

    function getFirstDayOfTheWeek() {
        var date = resetDate();
        date.setDate(1);
        return date.getDay();
    }

    function getLastDay() {
        var date = resetDate(),
            month = date.getMonth();
        date.setMonth(month + 1);
        date.setDate(0);
        return date.getDate();
    }

    function resetDaysTemplate() {
        return {
            DAY_0: '',
            DAY_1: '',
            DAY_2: '',
            DAY_3: '',
            DAY_4: '',
            DAY_5: '',
            DAY_6: ''
        };
    }

    function compileDaysTemplate(template, info) {
        return _.template(
            template,
            info
        );
    }

    function drawDays() {
        var firstDayOfTheWeek = getFirstDayOfTheWeek(),
            lastDay = getLastDay(),
            i,
            j = -1,
            info = resetDaysTemplate(),
            compiled ='';

        for (i = 1 - firstDayOfTheWeek, j = -1; i <= lastDay; i += 1 ) {
            if (++j > 6) {
                j = 0;

                compiled += compileDaysTemplate(
                    this.options.templates.days,
                    info
                );

                info = resetDaysTemplate();
            }
            if (i > 0) {
                info['DAY_' + j] = i;
            }
        }

        compiled += compileDaysTemplate(
            this.options.templates.days,
            info
        );

        this.$el.find('tbody').html(compiled);
    }

    function render () {
        this.$el.html(
            _.template(this.options.templates.scaffold, 
                _.extend(
                    CALENDAR, {
                        "CURRENT_DATE": this.currentDate
                    })
                )
            );

        return this;
    }

    $.fn.calendar = jQueryCalendar;
}(jQuery));
